package st.trade;

import java.util.Map;

import st.Stk;
import st.BasicStockData;

public class TransactionHandler {

	private double capacity = Stk.INIT_CAP;
	/** key = stockId, value=mount, 庫存 */
	private Map<BasicStockData, Integer> stocks;

	public TradeResult buy(BasicStockData stock, int qty) {
		Trade t = new Trade(stock, qty);
		double tradeAmount = t.getTradeAmount();
		if (tradeAmount > capacity) {
			return TradeResult.NO_MONEY;
		}
		capacity = capacity + tradeAmount;
		Integer stockQty = stocks.get(stock);
		if (stockQty == null || stockQty == 0) {
			stocks.put(stock, qty);
		} else {
			stocks.put(stock, stockQty + qty);
		}
		return TradeResult.OK;
	}

	public TradeResult sell(BasicStockData stock, int qty) {
		Trade t = new Trade(stock, -1 * qty);
		Integer stockQty = stocks.get(stock);
		if (stockQty == null || stockQty < qty) {
			return TradeResult.NO_STK;
		}
		capacity = capacity + t.getTradeAmount();
		stocks.put(stock, stockQty - qty);
		return TradeResult.OK;
	}

}
